﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LitJson;

[AddComponentMenu("PUEX/Affector/UV/UVScaleOverLifetime")]
public class PUEXUVScaleOverLifetimeAffector : PUEXAffector {

	#region - Editable property
	public PUEXDynamicAttribute scaleUOverLifetime;
	public PUEXDynamicAttribute scaleVOverLifetime;
	public bool useEmitterTime;
	#endregion
	
	#region - Lifecycle
	public PUEXUVScaleOverLifetimeAffector ()
	{
		scaleUOverLifetime = PUEXDynamicAttribute.GenerateFixed (1f);
		scaleVOverLifetime = PUEXDynamicAttribute.GenerateFixed (1f);
		useEmitterTime = false;
	}
	#endregion
	
	#region - Update
	public override void update (float dt, PUEXParticle particle)
	{
		float t = particle.timeFraction;
		if (useEmitterTime)
			t = inTrigger () ? triggerTimeFraction : ownerEmitter.timeFraction;

		int ut = (int)ownerEmitter.uvTiles.x > 0 ? (int)ownerEmitter.uvTiles.x : 1;
		int vt = (int)ownerEmitter.uvTiles.y > 0 ? (int)ownerEmitter.uvTiles.y : 1;
		
		particle.uvScale = Vector2.Scale (new Vector2(1f / ut, 1f / vt), new Vector2 (scaleUOverLifetime.getValue(t), scaleVOverLifetime.getValue(t)));
	}
	#endregion
	
	#region - Param property
	public override void updateParams (PUEXParticleSystem system)
	{
		scaleUOverLifetime.parameterize (system);
		scaleVOverLifetime.parameterize (system);
	}
	#endregion
	
	#region - Serialization
	public override JsonData save (JsonData emitterData, JsonData systemData)
	{
		JsonData ret = base.save (emitterData, systemData);
		
		ret ["scale_u_over_lifetime"] = PUEXUtils.serializeDynamicAttribute(scaleUOverLifetime);
		ret ["scale_v_over_lifetime"] = PUEXUtils.serializeDynamicAttribute(scaleVOverLifetime);
		ret ["use_emitter_time"] = useEmitterTime;
		
		return ret;
	}
	#endregion

}
